require(['zTreeCheckbox', 'grid'], function () {
    //========================================================变量
    var userInfo = commonFun.execParentMethod("getUserInfo");					//当前用户信息
    // 如果是最高管理员登录,可以让其看到所属公司
    var isAdminRole = userInfo.isAdminRole;										//是否最高管理员
    var funcId = "", 															//功能权限id
        $fieldsTab = $("#fieldsTab"), 											//字段权限列表
        $fieldGridDiv = $("#fieldGridDiv"), 									//字段权限表所在div
        trNode, 																//角色树节点
        ztree = null,															//功能权限树
        $sysRoleTree = $("#sysRoleTree"),										//角色树
        setting;																//角色树设置

    function initElements() {
        //加载权限按钮(暂时屏蔽，无按钮权限)
        //	commonFun.authorityLoad($("body"));

        //初始化权限树设置
        setting = {
            check: {
                enable: true,
                chkboxType: {
                    "Y": "ps",
                    "N": "ps"
                }
            },
            data: {
                keep: {
                    leaf: false,
                    parent: true
                },
                key: {
                    name: "name"
                },
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "funcId",
                    rootPid: null
                }
            },
            view: {
                showIcon: false
            },
            callback: {
                onClick: function (event, treeId, treeNode, clickFlag) {
                    trNode = treeNode;
                    // 显示对应的字段权限配置表
                    if (treeNode.type === "3") {
                        funcId = treeNode.id;
                        $fieldGridDiv.show();
                        loadFieldGrid();
                    } else {
                        funcId = "";
                        $fieldGridDiv.hide();
                    }
                    // 获取该功能对应字段
                    // loadFieldGrid();
                }
            }
        }
        initFieldsTabGrid();
        //初始化角色树
        initSysRoleTree();
        //字段权限部分默认隐藏
        $fieldGridDiv.hide();
    }

    function initFieldsTabGrid() {
        // 字段权限列表
        $fieldsTab.grid({
            url: "/sysAuthorityFunc/getCurrentFieldData.htm",
            showPager: false,
            width: 420,
            colModel: [{name: "id", key: true, label: 'id', hidden: true},
                {name: "tableDsc", label: '表名称', index: "tableDsc", width: "110"},
                {name: "fieldDsc", label: '字段名称', index: "fieldDsc"},
                {name: "fieldAlias", label: '字段别名', index: "fieldAlias", editable: true}],
            gridComplete: function () {
                var fieldIds = $fieldsTab.jqGrid("getDataIDs");
                var fieldId;
                for (var i in fieldIds) {
                    fieldId = fieldIds[i];
                    var fieldData = $fieldsTab.jqGrid("getRowData", fieldId);
                    var fieldAliasHtml = "<input type='text' fieldId='" + fieldId
                        + "' value='" + fieldData.fieldAlias
                        + "' class='u-input dataRow' style='width:140px;'/>";
                    $fieldsTab.jqGrid('setRowData', fieldId, {
                        fieldAlias: fieldAliasHtml
                    });
                }
                // 选中其已分配的资源权限数据
                if ($("#roleId").val() && funcId) {
                    $.ajaxExt({
                        // async:true,
                        url: "/sysAuthorityFunc/getCheckedFieldData.htm",
                        data: {
                            "roleId": $("#roleId").val(),
                            "funcId": funcId
                        }
                    }).done(function (data) {
                        for (var i in data) {
                            $fieldsTab.jqGrid("setSelection", data[i].id);
                        }
                    });
                }
            }
        });
    }

    /**
     * 加载字段权限列表
     */
    function loadFieldGrid() {
        //$fieldsTab.jqGrid("clearGridData");
        $fieldsTab.grid('setGridParam', {
            datatype: "json",
            postData: {
                roleId: $("#roleId").val(),
                level: $("#level").val(),
                "funcId": funcId
            }
        }).trigger("reloadGrid");
    }

    /**
     * 获得根节点并选中根节点
     */
    function getAndSelectRootNode() {
        var node = sysRoleTreeObj.getNodesByFilter(function (node) {
            return node.level == 0;
        }, true);
        sysRoleTreeObj.selectNode(node, false);
        sysRoleTreeClick(null, node.id, node, true);
    }

    /**
     * 点击树节点
     * @param event 事件
     * @param treeId ztree节点id
     * @param treeNode ztree节点
     * @param clickFlag 点击标识
     */
    function sysRoleTreeClick(event, treeId, treeNode, clickFlag) {
        $("#corpId").val(treeNode.corpId);
        $("#roleId").val(treeNode.id);
        $("#level").val(treeNode.level);
        $("#opr").val("clickTree");
        $fieldGridDiv.hide();
        // 自己的角色不允许修改
        if (isAdminRole === "0" && $("#level").val() === "0") {
            $("#saveAuthority").hide();
        } else {
            $("#saveAuthority").show();
        }
        //var treeNodes;
        $.ajaxExt({
            async: true,
            url: "/sysAuthorityFunc/getFuncTreeData.htm",
            data: {
                "roleId": treeNode.id,
                "level": treeNode.level
            }
        }).done(function (data) {
            if (!data) {
                data = [];
            }
            ztree = $('#tree').createTree(setting, data);
            // //展开父节点
            if (ztree) {
                var nodes = ztree.getNodes(),
                    root = nodes[0];
                ztree.expandNode(root, true, false, false);// 默认展开根节点
            }
            reloadTree();
        });
    }

    /**
     * 获得节点数据，并且生成左侧的树
     */
    function initSysRoleTree() {
        $.ajaxExt({
            async: true,
            url: "/sysRole/getSysRoleByName.htm"
        }).done(function (data) {
            if (!data) {
                data = [];
            }
            // 树的参数配置
            var setting = {
                data: {
                    key: {
                        name: "name"
                    },
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "parentRoleId",
                        rootPId: 0
                    }
                },
                view: {
                    showIcon: true
                },
                callback: {
                    onClick: sysRoleTreeClick
                }
            };
            // 生成树
            sysRoleTreeObj = $sysRoleTree.createTree(setting, data, {search: $('#search-text')});
            sysRoleTreeObj.setting.view.expandSpeed = "";
            sysRoleTreeObj.expandAll(true);
            sysRoleTreeObj.setting.view.expandSpeed = "fast";
            getAndSelectRootNode();// 选中根节点，触发事件
        });
    }

    /**
     * 根据角id色获得该角色的功能权限分配信息，勾选数据
     */
    function reloadTree() {
        $.ajaxExt({
            async: true,
            url: "/sysAuthorityFunc/getCheckedFuncData.htm",
            data: {
                "roleId": $("#roleId").val()
            }
        }).done(function (data) {
            // 全部取消勾选
            ztree.checkAllNodes(false);
            // 根据读取数据设置勾选
            if (data) {
                $.each(data, function (i, ctx) {
                    var node = ztree.getNodeByParam("id", ctx.id);
                    if (node) {
                        ztree.checkNode(node);
                    }
                });
            }
        });
    }

    // 点击保存《功能权限和字段权限的分配信息》
    $("#saveAuthority").click(function () {
        var funcParams = [], buttonParams = [], fieldIds = [], fieldAliases = [];
        if (funcId) {
            fieldIds = $fieldsTab.grid("getGridParam", "selarrrow"); // 获取选中的字段权限
            $('.dataRow').each(function (i) {
                for (var i in fieldIds) {
                    if ($(this).attr("fieldId") === fieldIds[i]) {
                        fieldAliases.push($(this).val());
                    }
                }
            });
        }
        // 获取选中节点的id
        var nodes = ztree.getCheckedNodes(true);
        for (var i in nodes) {
            // 判断是功能还是按钮 1--功能;2--按钮;3--列表的功能
            if (nodes[i].type === "1" || nodes[i].type === "3") {
                funcParams.push(nodes[i].id);
            } else if (nodes[i].type === "2") {
                buttonParams.push(nodes[i].id);
            }
        }
        var loadMask = $.createMask();
        $.ajaxExt({
            url: "/sysAuthorityFunc/saveFuncAuthority.htm",
            async: true,
            data: {
                "funcIds": funcParams,
                "buttonIds": buttonParams,
                "fieldIds": fieldIds,
                "fieldAliases": fieldAliases,
                "roleId": $("#roleId").val(),
                "ufuncId": funcId
            }
        }).done(function () {
            $.messager.alert("保存", "保存成功!", "msg",
                function () {
                    loadMask.remove();
                    // 重新载入ztree
                    reloadTree();
                    // 刷新
                    ztree.refresh();
                    // 刷新字段权限数据
                    loadFieldGrid();
                    //更新功能权限
                    commonFun.refreshFuncAuth();
                });
        });
    });
    // 全选事件
    $("#chkAll").on("click", function () {
        ztree.checkAllNodes(true);
    });
    // 反向全选事件
    $("#unchkAll").on("click", function () {
        ztree.checkAllNodes(false);
    });


    function resize() {
        var winHeight = $(window).height();

        //设置功能权限树高和宽
        $('#tree').css({
            height: winHeight - 111
        });
        //设置角色树高度
        $sysRoleTree.height(winHeight - 55);
        $("#left,#right").height(winHeight);
        $fieldGridDiv.height(winHeight - 100);
        if ($fieldsTab[0].hasChildNodes()) {
            $fieldsTab.grid('setGridHeight', winHeight - 137);
        }
    }

    $(window).on('resize', resize).trigger('resize');

    initElements();
});
